package cn.tedu.ximart.server.utils;

import cn.tedu.ximart.server.ex.ServiceException;
import cn.tedu.ximart.server.pojo.dto.PictureUploadSingleDTO;
import cn.tedu.ximart.server.pojo.vo.PictureSimpleVO;
import cn.tedu.ximart.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 储存图片,生成URL,并返回Picture对象
 * @author HCL
 * @date 2022/07/23 10:54
 **/
//@Component
@Slf4j
public class PictureUploadUtils {
    @Value("${custom.file-upload.server-local-path}")
    private String fileUploadServerLocalPath;
    @Value("${custom.file-upload.resource-host}")
    private String fileUploadResourceHost;

    public PictureSimpleVO uploadPicture(PictureUploadSingleDTO pictureDTO){
        PictureSimpleVO pictureVO = new PictureSimpleVO();
        MultipartFile picture = pictureDTO.getPicture();
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(picture.getInputStream());
        } catch (IOException e) {
            log.debug("图片转发成bufferImage失败,格式错误");
            e.printStackTrace();
            String message ="当前文件不是图片文件,无法存储";
            throw new ServiceException(ServiceCode.ERR_PICTURE_UPLOAD,message);
        }
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        pictureVO.setWidth(width);
        pictureVO.setHeight(height);
        //得到文件的原始文件名
        String picName = picture.getOriginalFilename();
        if (StringUtils.isEmpty(picName)) {
            String message = "图片名称不能为空";
            throw new ServiceException(ServiceCode.ERR_PICTURE_UPLOAD,message);
        }
        int index = picName.lastIndexOf(".");
        if (index==-1) {
            String message="图片后缀缺失";
            throw new ServiceException(ServiceCode.ERR_PICTURE_UPLOAD,message);
        }
        //得到文件名的后缀部分并小写
        String suffix = picName.substring(index).toLowerCase();
        if (!suffix.matches(".(png|jpg|jpeg|gif|img)")) {
            log.debug("图片解析后缀为:"+ suffix);
            String message = "文件后缀名称不规划,无法上传";
            throw new ServiceException(ServiceCode.ERR_PICTURE_UPLOAD,message);
        }
        //图片重命名
        String picNewName = UUID.randomUUID().toString()+suffix;
        //生成多级路径
        String path = generatorPath(pictureDTO.getHead());
        File dir = new File(fileUploadServerLocalPath, path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //上传
        try {
            picture.transferTo(new File(dir, picNewName));
        } catch (IOException e) {
            log.debug("当前图片:" + picName + "上传存储失败", e);
        }
        String url = fileUploadResourceHost + path + picNewName;
        pictureVO.setUrl(url);
        return pictureVO;
    }

    public static String generatorPath(String prefix){
        String baseStr = UUID.randomUUID().toString();
        StringBuffer pathBuilder = new StringBuffer();
        pathBuilder.append("/");
        pathBuilder.append(prefix);
        pathBuilder.append("/");
        for (int i = 0; i < 8; i++) {
            char charStr = 0;//可能为空
            if (i>(baseStr.length()-1)) {
                pathBuilder.append("0/");
                continue;
            }
            charStr = baseStr.charAt(i);
            pathBuilder.append(charStr);
            pathBuilder.append("/");
        }
        return pathBuilder.toString();
    }
}